﻿using Mobileterminal.Common;
using Mobileterminal.Dtos;
using MySqlX.XDevAPI.Common;
using Newtonsoft.Json;
using Sunny.UI;
using System;
using System.Collections.Generic;
using System.ComponentModel;
using System.Data;
using System.Diagnostics;
using System.Drawing;
using System.Linq;
using System.Net.Http;
using System.Text;
using System.Threading.Tasks;
using System.Windows.Forms;
using static System.Net.Mime.MediaTypeNames;
using static System.Windows.Forms.VisualStyles.VisualStyleElement;


namespace Mobileterminal.Forms
{
    public partial class AddInstrumentkitsForm : UIEditForm
    {
        public AddInstrumentkitsForm()
        {
            InitializeComponent();
            InitializeComponentAdvanced();
            InitializeComboBoxes();
        }


        #region 右侧器械包
        private void InitializeComponentAdvanced()
        {

            // 异步加载数据
            LoadComboBoxDataAsync();

        }

        /// <summary>
        /// 定义集合 
        /// </summary>
        private BindingList<AddInstrumentkitsvaluesDtos> _apparatusList = new BindingList<AddInstrumentkitsvaluesDtos>();

        // 修改规格列的数据源为强类型列表
        private readonly List<SpecItem> _specItems = new List<SpecItem>
{
    new SpecItem { Text = "消毒设备", Value = 0 },
    new SpecItem { Text = "清洗设备", Value = 1 }
};

        // 修改耐用属性列的数据源
        private readonly List<DurableItem> _durableItems = new List<DurableItem>
{
    new DurableItem { Text = "耐用品", Value = 0 },
    new DurableItem { Text = "一次性用品", Value = 1 }
};


        /// <summary>
        /// 初始化数据源
        /// </summary>
        private async void LoadComboBoxDataAsync()
        {
            try
            {

                // 初始化列配置
                uiDataGridView1.AutoGenerateColumns = false;
                uiDataGridView1.Columns.Clear();

                // 输入框列
                uiDataGridView1.Columns.Add(new DataGridViewTextBoxColumn
                {
                    DataPropertyName = "ApparatusNo",
                    HeaderText = "器械编号"
                });
                uiDataGridView1.Columns.Add(new DataGridViewTextBoxColumn
                {
                    DataPropertyName = "ApparatusName",
                    HeaderText = "器械名称"
                });

                // 规格列配置
                var specCol = new DataGridViewComboBoxColumn
                {
                    DataPropertyName = "Specification",
                    HeaderText = "规格",
                    ValueType = typeof(bool),
                    DisplayMember = "Text",  // 关键属性
                    ValueMember = "Value",   // 关键属性
                    DataSource = _specItems,
                    DisplayStyle = DataGridViewComboBoxDisplayStyle.ComboBox // 强制显示为下拉框
                };
                uiDataGridView1.Columns.Add(specCol);

                // 数量输入框
                uiDataGridView1.Columns.Add(new DataGridViewTextBoxColumn
                {
                    DataPropertyName = "Quantity",
                    HeaderText = "数量"
                });

                // 耐用属性列配置
                var durableCol = new DataGridViewComboBoxColumn
                {
                    DataPropertyName = "Durableproperties",
                    HeaderText = "耐用属性",
                    ValueType = typeof(int),
                    DisplayMember = "Text",
                    ValueMember = "Value",
                    DataSource = _durableItems,
                    DisplayStyle = DataGridViewComboBoxDisplayStyle.ComboBox // 强制显示为下拉框
                };
                uiDataGridView1.Columns.Add(durableCol);

                // 加载数据
                LoadData();

                // 启用新增行
                uiDataGridView1.AllowUserToAddRows = true;
                uiDataGridView1.AutoGenerateColumns = false;

            }
            catch (Exception ex)
            {
                UIMessageBox.ShowError($"加载数据失败：{ex.Message}");
            }
        }

        /// <summary>
        /// 加载数据源数据
        /// </summary>
        /// <exception cref="NotImplementedException"></exception>

        private async void LoadData()
        {
            uiDataGridView1.DataSource = _apparatusList;
            _apparatusList.Add(new AddInstrumentkitsvaluesDtos());
        }


        #endregion

        #region  左侧 包数据
        public static List<InstrumentkitsDto> instrums = new List<InstrumentkitsDto>();

        public class ComboBoxItem
        {
            public string Text { get; set; }
            public bool Value { get; set; }
        }
        private void InitializeComboBoxes()
        {
            // Sterilizamethod 下拉框
            uiComboBox1.DisplayMember = "Text";
            uiComboBox1.ValueMember = "Value";
            uiComboBox1.DataSource = new List<ComboBoxItem>
    {
        new ComboBoxItem { Text = "干热灭菌", Value = false},
        new ComboBoxItem { Text = "高压蒸汽灭菌", Value = true }
    };

            // Outerpackags 下拉框
            uiComboBox2.DisplayMember = "Text";
            uiComboBox2.ValueMember = "Value";
            uiComboBox2.DataSource = new List<ComboBoxItem>
    {
        new ComboBoxItem { Text = "无纺布", Value = false },
        new ComboBoxItem { Text = "塑料袋", Value = true }
    };

            // InstrumentkitsType 下拉框
            uiComboBox3.DisplayMember = "Text";
            uiComboBox3.ValueMember = "Value";
            uiComboBox3.DataSource = new List<ComboBoxItem>
    {
        new ComboBoxItem { Text = "通用包", Value = false },
        new ComboBoxItem { Text = "普通包", Value = true }
    };
        }

        #endregion


        #region 事件处理

        /// <summary>
        /// 处理下拉框选择事件
        /// </summary>
        /// <param name="sender"></param>
        /// <param name="e"></param>
        private void UiDataGridView1_EditingControlShowing(object sender, DataGridViewEditingControlShowingEventArgs e)
        {

          

        }

 
        #endregion

        public class SpecItem
        {
            public string Text { get; set; }
            public int Value { get; set; }
        }

        public class DurableItem
        {
            public string Text { get; set; }
            public int Value { get; set; }
        }


        private void AddInstrumentkitsForm_Load(object sender, EventArgs e)
        {

        }

        private void uiLabel5_Click(object sender, EventArgs e)
        {

        }

        private void uiLabel9_Click(object sender, EventArgs e)
        {

        }

        private void uiLabel10_Click(object sender, EventArgs e)
        {

        }
  


        private void uiDataGridView1_CellContentClick(object sender, DataGridViewCellEventArgs e)
        {

        }



        private void AddInstrumentkitsForm_Load_1(object sender, EventArgs e)
        {
  

        }

        private void comboBox_SelectedIndexChanged(object sender, int index)
        {


        }

        /// <summary>
        /// 处理数据错误
        /// </summary>
        /// <param name="sender"></param>
        /// <param name="e"></param>
        private void UiDataGridView1_DataError(object sender, DataGridViewCellEventArgs e)
        {
       /*     if (e.ColumnIndex == uiDataGridView1.Columns["Specification"].Index ||
          e.ColumnIndex == uiDataGridView1.Columns["Durableproperties"].Index)
            {
                MessageBox.Show("请从下拉列表中选择有效值！", "输入错误", MessageBoxButtons.OK, MessageBoxIcon.Warning);
              //  e.Cancel = true;  // 阻止继续编辑
            }*/



        }

        /// <summary>
        /// 点击按钮，添加一行数据
        /// </summary>
        /// <param name="sender"></param>
        /// <param name="e"></param>
        private void uiButton1_Click(object sender, EventArgs e)
        {
         
            var newRow = new AddInstrumentkitsvaluesDtos
            {
                ApparatusNo = "A1000100",    // 默认值
                ApparatusName= "手术刀",       // 默认值
                Specification = 0,       // 默认值
                Durableproperties = 0 ,       // 默认值
                Quantity = 0,       // 默认值
            };

            _apparatusList.Add(newRow);       // 绑定到数据源


       //     uiDataGridView1.DataSource = null;
            uiDataGridView1.DataSource = _apparatusList;

            // 设置新增行索引
            uiDataGridView1.CurrentCell = uiDataGridView1
                .Rows[uiDataGridView1.Rows.Count - 1]
                .Cells[0];
            // 自动滚动到最后一行
         //   uiDataGridView1.FirstDisplayedScrollingRowIndex = uiDataGridView1.RowCount - 1;
        }

     
        private async void uiComboBox1_SelectedIndexChanged(object sender, EventArgs e)
        {
           
        }

        private void uiLabel3_Click(object sender, EventArgs e)
        {

        }

        private void uiTextBox2_TextChanged(object sender, EventArgs e)
        {

        }
        /// <summary>
        /// 点击按钮，保存数据
        /// </summary>
        /// <param name="sender"></param>
        /// <param name="e"></param>
        private async void btnOK_Click(object sender, EventArgs e)
        {
            // 获取整型参数
            bool sterilizaMethod = uiComboBox1.SelectedValue != null ? (bool)uiComboBox1.SelectedValue : true;
            bool outerPackags = uiComboBox2.SelectedValue != null ? (bool)uiComboBox2.SelectedValue : true;
            bool instrumentkitsType = uiComboBox3.SelectedValue != null ? (bool)uiComboBox3.SelectedValue : true;
            //传参
            var pdata = new
            {
                InstrumentkitsId=0,
                InstrumentkitsNo = uiTextBox7.Text,
                InstrumentkitsName = uiTextBox1.Text,
                Effectdays = uiTextBox2.Text,
                Serviceprice = uiTextBox5.Text,
                Department =  uiTextBox3.Text,
                Sterilizamethod = sterilizaMethod,
                Outerpackags = outerPackags,
                InstrumentkitsType = instrumentkitsType,

                apparatus = _apparatusList.Select(a => new
                {
                    ApparatusNo = a.ApparatusNo,
                    ApparatusName = a.ApparatusName,
                    Specification = a.Specification,
                    ApparatusNnit= "",
                    ApparatusModel= "",
                    ApparatusPrice="",
                    Productionindustry="",
                    Durableproperties = a.Durableproperties,
                    Quantity = a.Quantity
                }).ToList()
            };
            string jsonParam = JsonConvert.SerializeObject(pdata);
            Debug.WriteLine("Sending JSON: " + jsonParam); // 调试输出
            try
            {
                HttpContent httpContent = new StringContent(jsonParam, Encoding.UTF8, "application/json");
                var json = await HttpClientHelper.ClientAsync("post", "https://localhost:7286/api/Instrumentkit/CreateInstrumentkit", true, httpContent);

                var result = JsonConvert.DeserializeObject<InstrumentkitsDto>(json);
                if (result != null)
                {
                    UIMessageTip.Show("添加成功");
                    this.DialogResult = DialogResult.OK;
                    this.Close();
                }
            }
            catch (Exception ex)
            {
                UIMessageBox.ShowError($"请求失败：{ex.Message}");
            }

        }

        private void uiLabel11_Click(object sender, EventArgs e)
        {

        }
    }
}
